import { reactive, onMounted } from 'vue'
import { format } from 'date-fns'
import { parseTime } from '@/common/common'
import { Project } from '@/service/modules/project/types'
import {
  connTestReq,
  delDatasourceReq,
  getDatasourceListReq,
  syncMetaReq
} from '@/service/modules/data-manage'

export function useTable() {
  const state = reactive({
    page: 1,
    limit: 10,
    count: 0,
    list: [],
    loading: false,
    currentRecord: {} as Project,
    modDatasourceModalShow: false
  })

  const getList = async () => {
    if (state.loading) return
    state.loading = true

    const { data, count } = await getDatasourceListReq({
      page: state.page,
      limit: state.limit
    })
    state.loading = false
    if (!data) throw Error()
    state.list = data.map((record: Project) => {
      record.createTime = record.createTime
        ? format(parseTime(record.createTime), 'yyyy-MM-dd HH:mm:ss')
        : ''
      record.updateTime = record.updateTime
        ? format(parseTime(record.updateTime), 'yyyy-MM-dd HH:mm:ss')
        : ''
      return record
    })
    state.count = count
  }

  const updateList = () => {
    if (state.list.length === 1 && state.page > 1) {
      --state.page
    }
    getList()
  }

  //同步元数据
  const syncMeta = async (id: number) => {
    if (state.loading) return
    await syncMetaReq(id)
    state.loading = false
  }
  //连接测试
  const connTest = async (id: number) => {
    await connTestReq({ id: id })
  }
  //删除数据源
  const delDatasource = async (id: number, name: string) => {
    window.$dialog.error({
      title: window.$t('dialog.dangerOpTitle'),
      content: window.$t('dataManage.delDatasourceTips') + name,
      positiveText: window.$t('dialog.positiveText'),
      negativeText: window.$t('dialog.negativeText'),
      onPositiveClick: async () => {
        const res = await delDatasourceReq(id)
        if (res.resp_code === 0) {
          getList()
        }
      }
    })
  }

  const onOperationClick = (
    data: { rowData: Project },
    type: 'syncMeta' | 'connTest' | 'modDatasource' | 'delDatasource'
  ) => {
    state.currentRecord = data.rowData
    switch (type) {
      case 'syncMeta':
        syncMeta(data.rowData.id)
        break
      case 'connTest':
        connTest(data.rowData.id)
        break
      case 'modDatasource':
        state.modDatasourceModalShow = true
        break
      case 'delDatasource':
        delDatasource(data.rowData.id, data.rowData.name)
        break
    }
  }

  const changePage = (page: number) => {
    state.page = page
    getList()
  }

  const changePageSize = (limit: number) => {
    state.page = 1
    state.limit = limit
    getList()
  }

  onMounted(() => {
    getList()
  })

  return {
    state,
    changePage,
    changePageSize,
    updateList,
    onOperationClick
  }
}
